package lib

import (
	"crypto/md5"
	"encoding/hex"
	"github.com/astaxie/beego"
	"os"
	"path"
	"strconv"
)

//create md5 string
func Strtomd5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	rs := hex.EncodeToString(h.Sum(nil))
	return rs
}

//password hash function
func Pwdhash(str string) string {
	return Strtomd5(str)
}

func StringsToJson(str string) string {
	rs := []rune(str)
	jsons := ""
	for _, r := range rs {
		rint := int(r)
		if rint < 128 {
			jsons += string(r)
		} else {
			jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
		}
	}

	return jsons
}

// 检查文件或目录是否存在
// 如果由 filename 指定的文件或目录存在则返回 true，否则返回 false
func Exist(filename string) bool {
	_, err := os.Stat(filename)
	return err == nil || os.IsExist(err)
}

func CreateHtmlFile(layout string, tpl string, sections map[string]string) error {
	viewpath := beego.BConfig.WebConfig.ViewsPath
	paths := make(map[string]string)
	paths["layout"] = viewpath + "/" + layout
	paths["tpl"] = viewpath + "/" + tpl
	for key, value := range sections {
		paths[key] = viewpath + "/" + value
	}
	for key, value := range paths {
		if exist := Exist(value); !exist {
			os.MkdirAll(path.Dir(value), 0666)
			f, err := os.Create(value)
			if err != nil {
				return err
			}
			defer f.Close() //释放资源，时刻不忘
			beego.Debug("Create File Success:(" + key + ")" + value)
		}
	}
	return nil
}
